<?php

require_once("classes/db_functions.php");
require_once("classes/functions.php");

$step = @$_GET["s"];
if(!$step){
	$step = 1;
}
$num = @$_GET["nr"];
if(!$num){
	$num = 500;
}
$start = ($step-1)*$num;



$db = new db_functions();
$fp = fopen("uldupl/ulice_duplikati_$start-".($start+$num).".csv","w") or die("Error opening file");

$ulice = $db->selectAssoc("SELECT * FROM ulice ORDER BY ulica_ime LIMIT $start,$num");
//print_rarray($ulice);

$out = "";
foreach ($ulice as $k=>$ulica){
	
	$kom = array();
	
	$q = "SELECT komitent_id "
		."FROM komitenti, adrese, ulice "
		."WHERE komitenti.komitent_adresa=adrese.adresa_id "
		."AND adrese.adresa_ul_id=ulice.ulica_id "
		."AND ulice.ulica_id=$k";
	
	$res = $db->select1($q);
	if($res[0]){
		foreach ($res as $v){
			if(array_search($v[0],$kom) === false){
				$kom[] = $v[0];
			}
		}
	}
	
	$q = "SELECT komdel_kom_id "
		."FROM komitenti_delatnosti, adrese, ulice "
		."WHERE komitenti_delatnosti.komdel_adresa_id=adrese.adresa_id "
		."AND adrese.adresa_ul_id=ulice.ulica_id "
		."AND ulice.ulica_id=$k";
	$res = $db->select1($q);
	if($res[0]){
		foreach ($res as $v){
			if(array_search($v[0],$kom) === false){
				$kom[] = $v[0];
			}
		}
	}
	
	$out .= "\r\n$k\t$ulica\t".count($kom);
	
}
$out = substr($out,2);
echo fwrite($fp,$out)." B written.";
echo '<br /><a href="'.$_SERVER['PHP_SELF'].'?s='.($step+1).'">'.($step+1).'</a>';
echo '<script>alert("Gotovo!")</script>';

?>